//
//  TuanGouVC.m
//  MyTest
//
//  Created by zhiyou on 16-4-18.
//  Copyright (c) 2016年 wangyang. All rights reserved.
//

#import "TuanGouVC.h"
#import "TuanGouCell.h"
#import "TuanGou.h"
#import "TuanCell.h"
#define BASE_TOPURL @"http://www.shihuo.cn/app_swoole_groupon/home?platform=ios&timestamp=1460368082&v=4.0.2&token=b12ea67999f9c87984733fa79c897fc6"
#define BASE_BOTTOMURL @"http://www.shihuo.cn/app_swoole_groupon/list?platform=ios&timestamp=1460368082&v=4.0.2&token=da66ebe902ecc6f09976483ed46a06fd&coming=0&order=rank&page=1"

@interface TuanGouVC () <UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) NSMutableArray *bannerArr;
@property (nonatomic, strong) NSMutableArray *infoArr;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;


@end

@implementation TuanGouVC
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    _bannerArr = [[NSMutableArray alloc] init];
    _infoArr = [[NSMutableArray alloc] init];
    _dataArr = [[NSMutableArray alloc] init];
    [self setBar];
    [self getData];
}
#pragma mark -- 初始化tableView
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, Width, Height-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerClass:[TuanGouCell class] forCellReuseIdentifier:@"cell"];
        self.tableView.tableHeaderView = [self headerView];
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TuanGouCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor grayColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:_infoArr[0]]];
    [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:_infoArr[1]]];
    [cell.imgView3 sd_setImageWithURL:[NSURL URLWithString:_infoArr[2]]];
    [cell.imgView4 sd_setImageWithURL:[NSURL URLWithString:_infoArr[3]]];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return _dataArr.count*210/2;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return self.collectionView;
}
#pragma mark -- 获取数据
- (void)getData
{
    [MyRequest getWithURL:BASE_TOPURL parameters:nil success:^(NSDictionary *dic) {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        arr = [[dic objectForKey:@"data"] objectForKey:@"bannerInfo"];
        for (NSDictionary *dic1 in arr) {
            [_bannerArr addObject:[dic1 objectForKey:@"pic"]];
        }
        
        NSMutableArray *arr1 = [[NSMutableArray alloc] init];
        arr1 = [[dic objectForKey:@"data"] objectForKey:@"specialInfo"];
        
        NSString *str = [[[dic objectForKey:@"data"] objectForKey:@"bestInfo"] objectForKey:@"img_path"];
        [_infoArr addObject:str];
        
        for (NSDictionary *dic2 in arr1) {
            NSString *str1 = [dic2 objectForKey:@"pic"];
            [_infoArr addObject:str1];
        }
        [self.view addSubview:self.tableView];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    [MyRequest getWithURL:BASE_BOTTOMURL parameters:nil success:^(NSDictionary *dic) {
        NSArray *arr = [[dic objectForKey:@"data"] objectForKey:@"dataInfo"];
        for (NSDictionary *dic1 in arr) {
            TuanGou *tuanGou = [[TuanGou alloc] initWithDictionary:dic1];
            [_dataArr addObject:tuanGou];
        }
        [_tableView reloadData];
        [_collectionView reloadData];
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -- 初始化collectionView

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        layout.itemSize = CGSizeMake((Width-30)/2, 200);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, Width, _dataArr.count*210/2) collectionViewLayout:layout];
        _collectionView.scrollEnabled = NO;
        _collectionView.backgroundColor = [UIColor grayColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[TuanCell class] forCellWithReuseIdentifier:@"TuanCell"];
    }
    return _collectionView;
}
#pragma mark -- UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TuanCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TuanCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    TuanGou *tuanGou = _dataArr[indexPath.row];
    cell.tuanGou = tuanGou;
    return cell;
}

#pragma mark -- 创建表头
- (UIView *)headerView
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4)];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4)];
    for (int i = 0; i < _bannerArr.count; i++) {
        
        // 图片坐标从0开始
        UIImageView * imageView=  [[UIImageView alloc] initWithFrame:CGRectMake(Width*i, 0, Width, Height/4)];
        NSURL *url = [NSURL URLWithString:_bannerArr[i]];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        imageView.image = image;
        imageView.tag = 1000+i;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToNext:)];
        tap.numberOfTapsRequired = 1;
        [imageView addGestureRecognizer:tap];
        
        [_scrollView addSubview:imageView];
    }
    _scrollView.contentSize = CGSizeMake(Width * _bannerArr.count, 120);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    _scrollView.delegate = self;
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, Height/4-20, Width, 20)];
    _pageControl.numberOfPages = _bannerArr.count;
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    [_pageControl addTarget:self action:@selector(pageControlChanged) forControlEvents:UIControlEventValueChanged];
    
    [headView addSubview:_scrollView];
    [headView addSubview:_pageControl];
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    
    return headView;
}
- (void)pageControlChanged
{
    [_scrollView setContentOffset:CGPointMake(_pageControl.currentPage *Width, 0) animated:YES];
    [_timer invalidate];
    _timer = nil;
}

- (void)changeImage
{
    // 定义一个静态变量,代表方向
    static int direction = 1;
    if (_scrollView.contentOffset.x == 0)
    {
        direction = 1;
    }
    if (_scrollView.contentOffset.x == Width*(_bannerArr.count-1))
    {
        direction = -1;
    }
    // 设置滚动视图的偏移量,带动画
    [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x+Width*direction, 0) animated:YES];
}

#pragma mark -- UIScrollViewDelegate
// 将要开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 开始拖拽时,把定时器关闭
    [_timer invalidate];
    _timer = nil;
}

//已经结束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
}

// 将要开始减速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    
}

// 已经结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
    // 结束减速把定时器重新开启
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_timer == nil)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
    
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
}
- (void)goToNext:(UIGestureRecognizer *)tap
{
    UIView *imgView = [tap view];
    NSLog(@"%ld",(long)imgView.tag);
}
#pragma mark -- 创建导航
- (void)setBar
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 64)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:bgView.frame];
    imageView.image = [UIImage imageNamed:@"topbar"];
    [bgView addSubview:imageView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 20, 50, 40);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"F_iocn_normal"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:backBtn];
    
    UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtn.frame = CGRectZero;
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"D_iocn_normal"] forState:UIControlStateNormal];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:menuBtn];
    
    [menuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView.mas_top).offset(20);
        make.right.offset(-10);
        make.width.offset(50);
        make.height.offset(40);
    }];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLab.text = @"识货团购";
    titleLab.font = [UIFont systemFontOfSize:20];
    [bgView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView.mas_centerX);
        make.centerY.equalTo(bgView.mas_centerY).offset(10);
    }];
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)showMenu
{
    static int count = 1;
    if (count%2 == 1) {
        [self setMenu];
    }else
    {
        [self hideView];
    }
    count ++;
}
- (void)setMenu
{
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(Width*2/3, 64, Width/3, 90)];
    _bgView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_bgView];
    
    NSArray *arr = @[@"首页",@"我的",@"消息"];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 30*i, Width/3, 30);
        button.tag = i;
        [button setTitle:arr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        [_bgView addSubview:button];
        _bgView.clipsToBounds = YES;
    }
}
- (void)hideView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    _bgView.frame = CGRectMake(Width*2/3, 64, 0, 0);
    [UIView commitAnimations];
}
- (void)clickButton:(UIButton *)button
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
